const Koa = require('koa');
const cors = require('@koa/cors');
const send = require('koa-send');
const logger = require('koa-logger');
const serve = require('koa-static');
const koaBody = require('koa-body');

// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();

const os = require('os');

const fs = require('fs');
const path = require('path');



const app = new Koa();


app.use(logger());

app.use(koaBody({
    multipart: true,
    formidable: {
        //上传文件存储目录
        uploadDir: path.join(__dirname, `/public/uploads/`),
        //允许保留后缀名
        keepExtensions: true,
        multipart: true,
    }
}));
app.use(cors());
app.use(serve(path.join(__dirname, '/public')));

// log request URL:
app.use(async function (ctx, next) {
    await next();
    if (ctx.body || !ctx.idempotent) return;
    ctx.body = 'error';
});


// add url-route:
router.get('/fileload/:name', async (ctx) => {
    const name = ctx.params.name;
    const path = `public/uploads/${name}`;
    ctx.attachment(path);
    await send(ctx, path);
  });
router.get('/api/getQuesInfoList', async (ctx, next) => {
    let data = {
        'test': '123445678',
        'test2': '123445678',
    };
    ctx.response.body = data;

});

router.post('/test', async (ctx, next) => {
    var name = ctx.params.test;
    let data = {
        'test': name || '123445678'
    };
    ctx.request.body = data
    console.log(ctx.request.body);
    ctx.body = ctx.request.body
});
router.post('/save', async (ctx, next) => {
    console.log(ctx);
    const file = ctx.request.files.files;
    const reader = fs.createReadStream(file.path);
    const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
    reader.pipe(stream);
    console.log('uploading %s -> %s', file.name, stream.path);
    ctx.response.body = "success"
});

router.get('/', async (ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
});



// add router middleware:
app.use(router.routes());


app.listen(3002);
console.log('app started at port 3000...');